package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.R;
import com.atguigu.common.utils.to.SkuReductionTo;
import com.atguigu.common.utils.to.SpuBoundTo;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.BaseAttrs;
import com.atguigu.gulimall.product.vo.Bounds;
import com.atguigu.gulimall.product.vo.Skus;
import com.atguigu.gulimall.product.vo.SpuSaveVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService  couponFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu的基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        this.savaBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",vo.getDecript()));
        spuInfoDescService.saveInfoDesc(descEntity);

        //3、保存spu的图片集  pms_spu_images
        spuImagesService.savaSpuImages(spuInfoEntity.getId(),vo.getImages());

        //4、保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        attrValueService.saveSpuImages(spuInfoEntity.getId(),baseAttrs);

        //5、远程服务===保存spu的积分信息gulimall_sms-》 sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.spuBoundsSave(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保护spu积分信息失败");
        }
        //6、保存当前spu对应的所有sku信息；

        List<Skus> skus = vo.getSkus();
        skus.forEach(sku ->{
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku,skuInfoEntity);
            skuInfoEntity.setBrandId(vo.getBrandId());
            skuInfoEntity.setCatalogId(vo.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            //TODO
            skuInfoEntity.setSkuDefaultImg("");
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            //6.1) sku的基本信息：pms_sku_info
            skuInfoDao.insert(skuInfoEntity);

            Long skuId = skuInfoEntity.getSkuId();

           List<SkuImagesEntity> skuImagesEntityList =  sku.getImages().stream().map(image -> {
                SkuImagesEntity imagesEntity = new SkuImagesEntity();
                imagesEntity.setImgUrl(image.getImgUrl());
                imagesEntity.setDefaultImg(image.getDefaultImg());
                imagesEntity.setSkuId(skuId);
                return imagesEntity;
            }).filter(item ->{
                //返回true就是需要，返回false就是剔除
                return  !StringUtils.isEmpty(item.getImgUrl());
           }).collect(Collectors.toList());
            //6.2) sku的图片信息：pms_sku_images
           skuImagesService.saveBatch(skuImagesEntityList);
            //TODO 没有图片路径的 无需保存

            List<SkuSaleAttrValueEntity> attrEntities = sku.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity attrEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, attrEntity);
                attrEntity.setSkuId(skuId);
                return attrEntity;
            }).collect(Collectors.toList());
            //6.3）sku的销售属性信息：pms_sku_sale_attr_value

            skuSaleAttrValueService.saveBatch(attrEntities);


            //6.4）、远程服务====sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            skuReductionTo.setSkuId(skuId);
            BeanUtils.copyProperties(sku,skuReductionTo);
            if(sku.getFullCount() > 0 || sku.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if(r1.getCode() != 0){
                    log.error("远程保护sku优惠信息失败");
                }
            }

        });



    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((w) ->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && "0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && "0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    private void savaBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

}